package com.wei.duowan.bbs.ui.adapter;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.wei.duowan.bbs.R;
import com.wei.duowan.bbs.model.NewsChannelBean;
import com.wei.duowan.bbs.ui.activity.BaseActivity;
import com.wei.duowan.bbs.utils.VibrateUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 作者：赵若位
 * 时间：2019/9/28 17:39
 * 联系方式：1070138445
 * 功能：
 */
public class NewsChannelAdapter extends BaseRecyclerViewAdapter<NewsChannelBean>
{
    private static final String TAG = NewsChannelAdapter.class.getSimpleName();

    private static final int TITLE = 0x102;//标题

    private boolean isChunked = false;//游戏栏目是否可选中
    private NewsChannelBean mOwner, mRecommend;//我的和推荐

    private ItemTouchHelper mHelper;


    public NewsChannelAdapter(AppCompatActivity activity, ItemTouchHelper helper)
    {
        super(activity, R.layout.layout_news_channel);
        mHelper = helper;
    }


    /*刷新数据*/
    public final void setNewData(@Nullable List<NewsChannelBean> paramList1, List<NewsChannelBean> paramList2)
    {
        mList.clear();
        isChunked = false;
        mList.add(getOwnerBean());
        mList.addAll(paramList1 == null ? new ArrayList<>() : paramList1);
        mList.add(getRecommendBean());
        mList.addAll(paramList2 == null ? new ArrayList<>() : paramList2);
        notifyDataSetChanged();
    }


    @Override
    public int getItemViewType(int position)
    {
        if (super.getItemViewType(position) == CONTENT && mList.get(position).getTitle())
        {
            return TITLE;
        }
        return super.getItemViewType(position);
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type)
    {
        if (type == TITLE)
        {
            return BaseViewHolder.getViewHolder(mActivity, LayoutInflater.from(mActivity.getApplicationContext())
                    .inflate(R.layout.layout_news_channel_title, parent, false));
        }
        return super.onCreateViewHolder(parent, type);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position)
    {
        if (getItemViewType(position) == TITLE)
        {
            NewsChannelBean data = mList.get(holder.getAdapterPosition());
            holder.setText(R.id.tv_title, data.getName())
                    .setText(R.id.tv_descript, data.getDescript())
                    .setText(R.id.tv_action, position == 0 ? (mResources.getString(isChunked ? R.string.complete : R.string.editor)) : data.getAction())
                    .setVisibility(R.id.tv_descript, TextUtils.isEmpty(data.getDescript()) ? View.GONE : View.VISIBLE)
                    .setVisibility(R.id.tv_action, TextUtils.isEmpty(data.getAction()) ? View.GONE : View.VISIBLE)
                    .setTextColor(R.id.tv_action, isChunked ? R.color.color : R.color.color9)
                    .setOnClickListener(R.id.tv_action, view ->
                    {
                        if (isChunked)
                        {
                            //完成
                            isChunked = !isChunked;
                            notifyDataSetChanged();
                            ((BaseActivity) mActivity).alert("编辑完成...");
                        } else
                        {
                            //编辑
                            VibrateUtils.getInstance().vibrate(200);
                            isChunked = !isChunked;
                            notifyDataSetChanged();
                        }
                    }).itemView.setOnClickListener(view ->
            {
                Log.e(TAG, "当前标题的位置:" + position);
                Log.e(TAG, "getAdapterPosition: " + holder.getAdapterPosition());
                Log.e(TAG, "indexofRecommend: " + indexofRecommend());
                Log.e(TAG, "getLayoutPosition: " + holder.getLayoutPosition());
            });
        } else
        {
            super.onBindViewHolder(holder, position);
        }
    }

    @Override
    protected void convert(int position, @Nullable BaseViewHolder holder, @Nullable NewsChannelBean data)
    {
        holder.setText(R.id.tv_title, data.getName())
                .setImageResource(R.id.img_action, holder.getLayoutPosition() < indexofRecommend() ? R.mipmap.icon_add : R.mipmap.icon_del)
                .setVisibility(R.id.img_action, isMoved(data) ? View.VISIBLE : View.GONE)
                .itemView.setOnLongClickListener(view ->
        {
            Log.e(TAG, "setOnLongClickListener: ");
            if (!isChunked)
            {
                VibrateUtils.getInstance().vibrate(200);
                isChunked = !isChunked;
                notifyDataSetChanged();
            }
            return true;
        });

        holder.itemView.setOnClickListener(view ->
        {
            Log.e(TAG, "setOnClickListener: ");
            if (isMoved(data))
            {
                int from = holder.getLayoutPosition();
                int to = from < indexofRecommend() ? mList.size() - 1 : indexofRecommend();
                onItemMoved(data, from, to);
            }
        });

        /*Item拖拽*/
        holder.itemView.setOnTouchListener((view, event) ->
        {
            Log.e(TAG, "setOnTouchListener: ");
            if (event.getAction() == MotionEvent.ACTION_DOWN
                    &&isChunked&&isDraged(holder.getAdapterPosition()))
            {
                if (mHelper != null)
                {
                    mHelper.startDrag(holder);
                }
            }
            return false;
        });
    }


    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView)
    {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager)
        {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup()
            {
                @Override
                public int getSpanSize(int position)
                {
                    return isDisplayEmpty() || getItemViewType(position) == TITLE ? gridManager.getSpanCount() : 1;
                }
            });
        }
    }

    /*我的频道*/
    private NewsChannelBean getOwnerBean()
    {
        if (mOwner == null)
        {
            mOwner = new NewsChannelBean();
            mOwner.setName(mResources.getString(R.string.owner_channel));
            mOwner.setR_type(NewsChannelBean.FIXED);
            mOwner.setDescript(mResources.getString(R.string.drag_sorting));
            mOwner.setTitle(true);
            mOwner.setAction(mResources.getString(R.string.editor));
        }
        return mOwner;
    }

    /*推荐频道*/
    private NewsChannelBean getRecommendBean()
    {
        if (mRecommend == null)
        {
            mRecommend = new NewsChannelBean();
            mRecommend.setName(mResources.getString(R.string.owner_channel));
            mRecommend.setR_type(NewsChannelBean.FIXED);
            mRecommend.setDescript(null);
            mRecommend.setTitle(true);
            mRecommend.setAction(null);
        }
        return mRecommend;
    }

    /*获取推荐下标位置*/
    private int indexofRecommend()
    {
        return mList.indexOf(getRecommendBean());
    }

    /*Item是否可以移动*/
    private boolean isMoved(@Nullable NewsChannelBean data)
    {
        return isChunked && data.getR_type() != NewsChannelBean.FIXED;
    }

    /*Item移动逻辑*/
    private void onItemMoved(@Nullable NewsChannelBean data, int from, int to)
    {
        mList.remove(data);
        mList.add(to, data);
        notifyItemMoved(from, to);
        notifyItemChanged(to);
    }

    /*Item是否可以拖拽*/
    public boolean isDraged(int position)
    {
        NewsChannelBean data = mList.get(position);
        return isChunked && (!data.getTitle()) && data.getR_type() != NewsChannelBean.FIXED && position < indexofRecommend();
    }

    /*Item拖拽过程是否可以交换*/
    public boolean isSwap(int position)
    {
        NewsChannelBean data = mList.get(position);
        return position != 0 && position != indexofRecommend() &&
                position < indexofRecommend() && data.getR_type() != NewsChannelBean.FIXED;
    }

    /*Item的拖拽逻辑*/
    public void onItemDraged(int from, int to)
    {
        Collections.swap(mList, from, to);
        notifyItemMoved(from, to);
    }


    /*调试Data数据打印*/
    private void log()
    {
        for (NewsChannelBean data : mList)
        {
            if (data.getTitle())
            {
                Log.e(TAG, "===================================================");
                Log.e(TAG, data.getName());
                Log.e(TAG, "===================================================");
            } else
            {
                Log.e(TAG, data.getName());
            }
        }
    }
}
